package com.android.tiango.baba.act;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseApplication;
import com.android.tiango.baba.BaListActivity;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.db.Area;
import com.android.tiango.baba.db.AssetsDatabaseManager;
import com.android.tiango.baba.db.City;
import com.android.tiango.baba.db.DbHelper;
import com.android.tiango.baba.db.Province;
import com.android.tiango.baba.entity.AddressEnity;
import com.android.tiango.baba.entity.AddressModel;
import com.android.tiango.baba.entity.OneAddressEnity;
import com.android.tiango.baba.entity.OrderEntity;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.view.PullListView.PullListViewListener;
import com.j256.ormlite.dao.Dao;

public class ActAdressList extends BaListActivity<AddressModel> implements
		OnClickListener, PullListViewListener {

	
	
	private ArrayList<AddressModel> mArrayData;
	public int mWidth;
	private int mPosition;
	private DbHelper helper;
	private int ischeck = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		setTitleName("设置地址");
		if (null != mTitleBar) {
			mTitleBar.setBackIcon(R.drawable.back);
			setBackOnClickListener();
			mTitleBar.setMoreText("添加");
			mTitleBar.setMoreTextOnClickListener(this);
		}
		

		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.address_check_on);
		mWidth = bitmap.getWidth();
		mListView.setDivider(getResources().getDrawable(
				R.drawable.divider_address));
		mListView.setPullListener(this);
		mListView.startOnRefresh();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.tv_more:
			showActivity(ActAddAddress.class, false);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		mListView.startOnRefresh();
	}

	@Override
	protected View getItemView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		LayoutInflater inflater = getLayoutInflater();
		mPosition = position;
		
		final viewHolder viewholder;
		if (convertView == null) {
			viewholder = new viewHolder();
			convertView = inflater.inflate(R.layout.item_addresslist, null);
			viewholder.name = (TextView) convertView.findViewById(R.id.tv_name);
			viewholder.phone = (TextView) convertView
					.findViewById(R.id.tv_phone);
			viewholder.address = (TextView) convertView
					.findViewById(R.id.tv_address1);
			viewholder.address_detail = (TextView) convertView
					.findViewById(R.id.tv_address2);
			viewholder.edit = (Button) convertView.findViewById(R.id.bt_edit);
			viewholder.delete = (Button) convertView
					.findViewById(R.id.bt_delete);
			viewholder.isCheck = (ImageView) convertView
					.findViewById(R.id.iv_checkbox);
			viewholder.content = (LinearLayout) convertView
					.findViewById(R.id.ll_content);
			viewholder.address_hsview = (HorizontalScrollView) convertView
					.findViewById(R.id.address_hsview);

			LayoutParams lp= viewholder.content.getLayoutParams();
			lp.width = BaBaseApplication.mWidth;
			
			convertView.setTag(viewholder);
		} else {
			viewholder = (viewHolder) convertView.getTag();
		}
		 AddressModel bean = mAdapter.getItem(position);

		if (null != bean) {
			String coutyId = bean.getAreaId();
			String addressID = bean.getAddressId();
			String address = initCityCode(Integer.valueOf(coutyId));
			String isDefault = bean.getIsDefault();
			
			viewholder.delete.setTag(bean);
			viewholder.edit.setTag(bean);
			viewholder.isCheck.setTag(bean);
			
			viewholder.address.setText(address);
			viewholder.address_detail.setText(bean.getDetailAddress());
			viewholder.name.setText(bean.getShipName());
			viewholder.phone.setText(bean.getPhoneNumber());
			if ("1".equals(isDefault)) {
				viewholder.isCheck
						.setImageResource(R.drawable.address_check_on);
				viewholder.isCheck.setEnabled(false);
			} else {
				viewholder.isCheck.setEnabled(true);
				viewholder.isCheck
						.setImageResource(R.drawable.address_check_un);
			}
			
			viewholder.address_hsview.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					float downX = 0,downY=0;
					View view = (HorizontalScrollView) v;
					//View view = ((HorizontalScrollView) v).getChildAt(0);
					
					// 判断是否滑动栏到底了，如果是，就让iv这个图片隐藏，否则显示
					if (view.getMeasuredWidth() <= v.getScrollX()
							+ v.getWidth()-200) {
						viewholder.isCheck.setVisibility(View.INVISIBLE);
					} else {
						viewholder.isCheck.setVisibility(View.VISIBLE);
					}
					/*switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						downX=event.getX();
						downY=event.getY();
						break;
					case MotionEvent.ACTION_MOVE:
						
						break;
					case MotionEvent.ACTION_UP:
						
						if(downX-event.getX()>10){
							view.scrollTo(viewholder.delete.getWidth()+viewholder.edit.getWidth(), 0);
							viewholder.isCheck.setVisibility(View.INVISIBLE);
						}else if(event.getX()-downX>10){
							view.scrollTo(0, 0);
							viewholder.isCheck.setVisibility(View.VISIBLE);
						}
						break;
					default:
						break;
					}*/
					return false;
				}
			});
			viewholder.edit.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AddressModel newBean = (AddressModel) v.getTag();
					EditData(newBean.getAddressId());

				}
			});
			viewholder.isCheck.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AddressModel newBean = (AddressModel) v.getTag();					
					SetDefaultData(newBean.getAddressId());// 设置默认地址
					
				}
			});

			viewholder.delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					AddressModel newBean = (AddressModel) v.getTag();
					deleteData(newBean.getAddressId());
					

				}
			});
		}
		return convertView;
	}

	class viewHolder {
		private TextView name, phone, address, address_detail;
		private Button edit, delete;
		private ImageView isCheck;
		private LinearLayout content;
		private HorizontalScrollView address_hsview;
	}

	private String initCityCode(int coutyId) {
		AssetsDatabaseManager.initManager(getApplicationContext());
		AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();
		mg.getDatabase("ormlite.db");
		helper = new DbHelper(this);
		String arName = "";
		String cityName = "";
		String prName = "";
		try {
			Dao<Province, Integer> dataPro = helper.getProvinceDao();
			Dao<City, Integer> daoCityD = helper.getCityDao();
			Dao<Area, Integer> daoAreaD = helper.getAreaDao();
			List<Area> listArea = daoAreaD.queryForEq("areaId", coutyId);
			if (null != listArea && listArea.size() > 0) {
				Area arBean = listArea.get(0);
				int cityId = arBean.getCityId();
				int prId = arBean.getProvinceId();
				arName = arBean.getAreaName();
				List<City> cityList = daoCityD.queryForEq("cityId", cityId);
				if (null != cityList && cityList.size() > 0) {
					City cityBean = cityList.get(0);
					cityName = cityBean.getCityName();
					List<Province> prList = dataPro.queryForEq("provinceId",
							prId);
					if (null != prList && prList.size() > 0) {
						Province prBean = prList.get(0);
						prName = prBean.getProvinceName();
					}
				}

			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		StringBuffer sb = new StringBuffer();
		sb.append(prName);
		sb.append("  ");
		sb.append(cityName);
		sb.append("  ");
		sb.append(arName);
		sb.append("  ");
		return sb.toString();
	}

	// 编辑
	private void EditData(String addressId) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpparams = new HttpParams();
		httpparams.put("token", ShareCookie.getToken());// taken
		httpparams.put("addressId", addressId);
		client.get(HttpUrl.getUrl(HttpUrl.ONEADDRESS), httpparams,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object arg0) {
						// TODO Auto-generated method stub

						OneAddressEnity oneAddressEnity = (OneAddressEnity) arg0;
						AddressModel addressmodel = oneAddressEnity.getData();
						Intent intent = new Intent(ActAdressList.this,
								ActEditAddress.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable(Constants.DATA, addressmodel);
						intent.putExtras(bundle);
						startActivity(intent);
						ToastUtils.showMessage("成功获取！");

					}

					@Override
					public void onHttpStarted() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						// TODO Auto-generated method stub
						dismissWaitingDialog();
						ToastUtils.showMessage("地址列表获取失败！===" + arg1);
						if (mPageIndex > 1) {
							mPageIndex -= 1;
						}
						arg0.printStackTrace();

						mListView.onRefreshFinish();
						mListView.onLoadFinish();
					}
				}, OneAddressEnity.class);//
	}

	// 设置默认地址
	private void SetDefaultData(String addressId) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpparams = new HttpParams();
		httpparams.put("token", ShareCookie.getToken());// taken
		Log.e("ff", ShareCookie.getToken());
		System.out.println(ShareCookie.getToken());
		httpparams.put("addressId", addressId);// ID
		client.post(HttpUrl.getUrl(HttpUrl.SETDEFAULT), httpparams,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object arg0) {
						// TODO Auto-generated method stub
						ToastUtils.showMessage("设置默认地址cheng功");
						mListView.startOnRefresh();
					}

					@Override
					public void onHttpStarted() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						// TODO Auto-generated method stub

						ToastUtils.showMessage("设置默认地址失败！===" + arg1);

						arg0.printStackTrace();

						
					}
				});
	}

	// 删除
	private void deleteData(String addressId) {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpparams = new HttpParams();
		httpparams.put("token", ShareCookie.getToken());// taken
		httpparams.put("addressId", addressId);// taken
		client.post(HttpUrl.getUrl(HttpUrl.DELETEADDRESS), httpparams,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object arg0) {
						// TODO Auto-generated method stub
						dismissWaitingDialog();
						
						mListView.startOnRefresh();
						
					}

					@Override
					public void onHttpStarted() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						// TODO Auto-generated method stub
						dismissWaitingDialog();
						ToastUtils.showMessage("删除地址失败！===" + arg1);

						arg0.printStackTrace();

						mListView.onRefreshFinish();
						mListView.onLoadFinish();
					}
				});
	}

	// 加载列表
	private void loadData() {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpparams = new HttpParams();
		httpparams.put("token", ShareCookie.getToken());// taken

		client.get(HttpUrl.getUrl(HttpUrl.AddRESSLIST), httpparams,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object arg0) {
						// TODO Auto-generated method stub
						dismissWaitingDialog();
						AddressEnity addressenity = (AddressEnity) arg0;
						mArrayData = addressenity.getData();
						if (null != mArrayData) {
							mAdapter.putData(mArrayData);
						}
						ToastUtils.showMessage("成功获取！");
						mListView.onRefreshFinish();
						mListView.onLoadFinish();
					}

					@Override
					public void onHttpStarted() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						// TODO Auto-generated method stub
						dismissWaitingDialog();
						ToastUtils.showMessage("地址列表获取失败！===" + arg1);
						if (mPageIndex > 1) {
							mPageIndex -= 1;
						}
						arg0.printStackTrace();

						mListView.onRefreshFinish();
						mListView.onLoadFinish();
					}
				}, AddressEnity.class);//
	}

	@Override
	public void onPullRefresh() {
		// TODO Auto-generated method stub
		mPageIndex = 1;
		loadData();
	}

	@Override
	public void onPullLoadMore() {
		// TODO Auto-generated method stub
		mPageIndex += 1;
		loadData();
	}

}
